import pytest
from common.db_operation import DB
from common.http_requests import HttpRequests
from config.config import Config

@pytest.fixture(scope="session")
def init_db():
    """会话级夹具，初始化数据库连接，整个测试会话只执行一次"""
    db = DB()
    yield db
    db.conn.close()  # 测试结束关闭连接

@pytest.fixture(scope="function")
def get_token(init_db):
    """函数级夹具，获取接口 token（可结合数据库或登录接口获取）"""
    # 假设通过查询数据库获取已存在的 token
    sql = "select token from user_token where user_id = 'test_user'"
    token_result = init_db.execute_sql(sql)
    token = token_result[0]['token'] if token_result else None
    # 若 token 不存在，调用登录接口获取
    if not token:
        http = HttpRequests()
        login_data = {"username": "test_user", "password": "123456"}
        login_response = http.post("/user/login", json=login_data)
        token = login_response['token']
    yield token